package org.seckill.service.impl;

import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessKilledDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.entity.Seckill;
import org.seckill.entity.SuccessKilled;
import org.seckill.enums.SeckillStatuEnum;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

/**
 * 业务接口的实现
 * Created by Jungle on 2016/11/8.
 */
// @Component  所有的组件，在不知道具体的含义时可使用 @Service @Dao @Controller
@Service
public class SeckillServiceImpl implements SeckillService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 加入对DAO的注入
    @Autowired
    private SeckillDao seckillDao;

    @Autowired
    //@Qualifier("successKilledDao")
    private SuccessKilledDao successKilledDao;

    // 用于混淆MD5
    private String slat = "wefwejfiowu039f23i3fjlsfjlifjlwefjwjepf@#i2323f";

    public List<Seckill> getSeckillList() {

        return seckillDao.queryAll(0,100);
    }

    public Seckill getById(long seckillId) {

        return seckillDao.queryById(seckillId);
    }

    public Exposer exportSeckillUrl(long seckillId) {
        Seckill seckill = seckillDao.queryById(seckillId);
        if(seckill == null){
            return new Exposer(false,seckillId);
        }

        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
        // 系统当前时间
        Date nowTime = new Date();
        if(nowTime.getTime() < startTime.getTime()
                 || nowTime.getTime() > endTime.getTime()){
            return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
        }
        String md5 = this.getMD5(seckillId);
        return new Exposer(true,md5,seckillId);


    }

    /**
     * 根据秒杀ID生成MD5值，用于执行校验
     * @param seckillId
     * @return
     */
    private String getMD5(long seckillId){
        String base = seckillId + "/" + this.slat;
        return DigestUtils.md5DigestAsHex(base.getBytes());
    }

    @Transactional
    /**
     * 使用注解控制事务的优点 @Transactional
     * 1、开发团队达成一定约定，明确标注事务方法的白编程风格
     * 2、保证事务方法的执行时间尽可能的短，不要穿插其它的网络操作RPC/HTTP请求剥离到方法的外部
     * 3、不是所有的方法都需要事务，如：只有一条修改操作，只读操作不需要事务控制
     */
    public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException, RepeatKillException, SeckillCloseException {

        if(md5 == null || !md5.equals(this.getMD5(seckillId))){
            throw new SeckillException("seckill data  invalid");
        }

        try {
            //执行秒杀逻辑：1、减库存 2、记录秒杀行为
            int updateCount = seckillDao.reduceNumber(seckillId, new Date());
            if(updateCount <= 0 ){
                // 没有更新记录：秒杀结果（可能包含活动结束或者库存已经完毕）
                throw new SeckillCloseException("seckill is close");
            }else{
                int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
                if(insertCount <= 0 ){
                    //重复秒杀
                    throw new RepeatKillException("repeat seckill ");
                }else{
                    // 秒杀成功
                    SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
                    return new SeckillExecution(seckillId, SeckillStatuEnum.DATA_ERROR.SUCCESS,successKilled);
                }
            }
        }catch (RepeatKillException e1){
            throw e1;
        }catch (SeckillCloseException e2){
            throw e2;
        }catch (Exception e) {
            logger.error(e.getMessage(),e);
            // 所有编译期异常转换为运行期异常
            throw new SeckillException("seckill error " + e.getMessage());
        }

    }
}
